package plugins.flavours;

import java.util.Map;
import java.util.HashMap;

import plugins.Plugin;

import main.Room;
import main.User;


public class SmsPlugin extends Plugin {

	private Map<String, String> addressMap;
	private HTTPpost post;
	
	public SmsPlugin() {
		 addressMap = new HashMap<String, String>();
		 addressMap.put("serge", "http://kogepan.rosemary.ee/sms/s/index.php");
		 addressMap.put("raido", "http://www.tmk.edu.ee/~ksadem/r/index.php");
		 addressMap.put("kristiine", "http://www.tmk.edu.ee/~ksadem/k/index.php");
		 post = new HTTPpost();
	}


	@Override
	public void execute(Room room, User user, String command, String text) {
		try {
			if((post.prepareAndPost(addressMap.get(text.split(" ")[0].toLowerCase()), "nimi",
					user.name, "sms", removeCommandFromLine(text)).indexOf("Saadetud!") > -1) ||
					(post.prepareAndPost(addressMap.get(text.split(" ")[0].toLowerCase()), "nimi",
		               user.name, "sms", removeCommandFromLine(text)).indexOf("ks teele") > -1))	
				room.dispatchRoomMsg(user, "Successful!");
			else
				room.dispatchRoomMsg(user, "Sending failed!");
		} catch (Exception e) {
			room.dispatchRoomMsg(user, "Sending failed with a serious error!");
//			e.printStackTrace();
		}
		
	}	

	
	/**
	    * Removes the first word (command [/ls, /list]) from the string
	    */
	   private String removeCommandFromLine(String command) {
	      String[] words = command.split(" ");
	      String newLine = "";
	      if (words.length <= 1) {
	         return "";
	      }
	      for (int i = 1; i < words.length; i++) {
	         newLine += words[i];
	         if (i+1 < words.length) {
	            newLine += " ";
	         }
	      }
	      return newLine;
	   }
}
